import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class DormitoryDeleter:
    def __init__(self):
        self.db = Database()
    
    def delete_dormitory(self, building, room_number):
        """
        删除宿舍
        
        参数:
            building (str): 宿舍楼号
            room_number (str): 房间号
        
        返回:
            bool: 删除成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not building or not room_number:
                print("错误：楼号和房间号都必须填写")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT id, current_count FROM dormitory WHERE building = ? AND room_number = ?",
                (building, room_number)
            )
            dormitory = self.db.cursor.fetchone()
            
            if not dormitory:
                print(f"错误：宿舍 {building}-{room_number} 不存在")
                return False
            
            dormitory_id, current_count = dormitory
            
            # 检查宿舍是否有学生
            if current_count > 0:
                print(f"错误：宿舍 {building}-{room_number} 当前有 {current_count} 名学生，无法删除")
                return False
            
            # 检查是否有维修记录
            self.db.cursor.execute(
                "SELECT COUNT(*) FROM maintenance WHERE dormitory_id = ? AND status = 'pending'",
                (dormitory_id,)
            )
            pending_maintenance = self.db.cursor.fetchone()[0]
            
            if pending_maintenance > 0:
                print(f"错误：宿舍 {building}-{room_number} 有待处理的维修记录，无法删除")
                return False
            
            # 删除宿舍
            self.db.cursor.execute(
                "DELETE FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            self.db.conn.commit()
            
            print(f"成功：宿舍 {building}-{room_number} 已删除")
            return True
        except Exception as e:
            print(f"错误：删除宿舍时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def delete_dormitories(self, dormitory_ids):
        """
        批量删除宿舍
        
        参数:
            dormitory_ids (list): 宿舍ID列表
        
        返回:
            tuple: (成功删除数量, 总数量)
        """
        success_count = 0
        total_count = len(dormitory_ids)
        
        try:
            self.db.connect()
            
            for dormitory_id in dormitory_ids:
                # 检查宿舍是否有学生
                self.db.cursor.execute(
                    "SELECT building, room_number, current_count FROM dormitory WHERE id = ?",
                    (dormitory_id,)
                )
                dormitory = self.db.cursor.fetchone()
                
                if not dormitory:
                    print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                    continue
                
                building, room_number, current_count = dormitory
                
                if current_count > 0:
                    print(f"错误：宿舍 {building}-{room_number} 当前有 {current_count} 名学生，无法删除")
                    continue
                
                # 检查是否有维修记录
                self.db.cursor.execute(
                    "SELECT COUNT(*) FROM maintenance WHERE dormitory_id = ? AND status = 'pending'",
                    (dormitory_id,)
                )
                pending_maintenance = self.db.cursor.fetchone()[0]
                
                if pending_maintenance > 0:
                    print(f"错误：宿舍 {building}-{room_number} 有待处理的维修记录，无法删除")
                    continue
                
                # 删除宿舍
                self.db.cursor.execute(
                    "DELETE FROM dormitory WHERE id = ?",
                    (dormitory_id,)
                )
                self.db.conn.commit()
                
                print(f"成功：宿舍 {building}-{room_number} 已删除")
                success_count += 1
            
            return success_count, total_count
        except Exception as e:
            print(f"错误：批量删除宿舍时发生错误 - {str(e)}")
            return success_count, total_count
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    deleter = DormitoryDeleter()
    
    print("===== 宿舍删除 =====")
    print("1. 删除单个宿舍")
    print("2. 批量删除宿舍")
    
    choice = input("请选择操作 (1-2): ")
    
    if choice == '1':
        building = input("请输入宿舍楼号: ")
        room_number = input("请输入房间号: ")
        deleter.delete_dormitory(building, room_number)
    
    elif choice == '2':
        # 先查询所有宿舍
        from query_dormitory import DormitoryQuery
        query = DormitoryQuery()
        dormitories = query.query_all_dormitories()
        
        if not dormitories:
            print("没有找到任何宿舍信息")
        else:
            print("\n宿舍ID\t楼号\t房间号\t容量\t当前人数\t状态")
            for dorm in dormitories:
                print(f"{dorm[0]}\t{dorm[1]}\t{dorm[2]}\t{dorm[3]}\t{dorm[4]}\t\t{dorm[5]}")
            
            ids_input = input("\n请输入要删除的宿舍ID，多个ID用逗号分隔: ")
            try:
                dormitory_ids = [int(id.strip()) for id in ids_input.split(',')]
                success_count, total_count = deleter.delete_dormitories(dormitory_ids)
                print(f"\n批量删除完成：成功 {success_count}/{total_count}")
            except ValueError:
                print("错误：ID必须是数字")
    
    else:
        print("无效的选择")